﻿using Missbot.Common;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Model.MsgCmds.Notes;
using Missbot.Model.MsgInfos;
using Newtonsoft.Json;

namespace Missbot.Core.Channels
{
    [UsedImplicitly]
    public class MentionChannel : IMsgChannel
    {
        public override string Name => "mention";
        public override ChannelType BindingType => ChannelType.Mention;
        public override string ChannelFlag => "mention";

        private static InstanceConfig InstanceConfig => Configger<AIConfigBase>.AIConfig.Instance;

        protected override void Send(OutboxDTO dto)
        {
            MsgSender.PushMsg(dto.FileIDs.IsNullOrEmpty()
                                  ? new CreateNoteSpecifiedCmd
                                  {
                                      Text = dto.Text,
                                      ReplyId = dto.SourceID,
                                      VisibleUserIds = new[] { dto.User.ID }
                                  }
                                  : new CreateNoteSpecifiedWithFileCmd
                                  {
                                      Text = dto.Text,
                                      ReplyId = dto.SourceID,
                                      VisibleUserIds = new[] { dto.User.ID },
                                      FileIDs = dto.FileIDs
                                  });
        }

        protected override InboxSession ParseDataImpl(string msg)
        {
            var mentionInfo = JsonConvert.DeserializeObject<MentionInfo>(msg);
            if (mentionInfo?.Body == null)
            {
                return null;
            }

            var mentionBody = mentionInfo.Body.Body;
            var botFullName = $"@{InstanceConfig.BotUserName}@{InstanceConfig.LocalHost}";
            var botName = $"@{InstanceConfig.BotUserName}";
            mentionBody.Text = mentionBody.Text.Replace(botFullName, "").Replace(botName, "").Trim();

            return new InboxSession
            {
                Channel = this,
                Files = mentionBody.Files,
                SourceID = mentionBody.ID,
                User = mentionBody.User,
                Text = mentionBody.Text,
                Group = new InstanceGroup { ID = mentionBody.User.Host }
            };
        }
    }
}